package com.badibadi.adapter;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;

import net.tsz.afinal.FinalBitmap;

import com.badibadi.activity.ActivityReadingActivity;
import com.badibadi.activity.MyDataActivity;
import com.badibadi.infos.ActivityListModel;
import com.badibadi.infos.ActivityReadingModel;
import com.badibadi.infos.Results;
import com.badibadi.infos.User;
import com.badibadi.infos.UserInfoModel;
import com.badibadi.mytools.Constants;
import com.badibadi.mytools.JSONUtils;
import com.badibadi.mytools.MyThreadTool;
import com.badibadi.mytools.Utils;
import com.badibadi.uniclubber.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class XListView1Adapter_2 extends BaseAdapter {
	private Context context;
	private List<ActivityListModel> activityListModels;
	private DisplayImageOptions options;
	private Message mes;
	private Bundle bun;
	private String uid;
	private UserInfoModel userInfoModel;
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				Utils.ExitPrgress(context);
				try {
					Utils.showMessage(context, context.getResources()
							.getString(R.string.l_net_error));
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 2:

				try {
					Utils.ExitPrgress(context);
					Utils.showMessage(context, msg.getData().getString("结果"));
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 3:

				try {
					Utils.ExitPrgress(context);
					Utils.showMessage(context, context.getResources()
							.getString(R.string.l_xb113));
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;

			default:
				break;
			}
		}
	};

	public XListView1Adapter_2(Context context,
			List<ActivityListModel> activityListModels
		) {
		this.activityListModels = activityListModels;
		this.userInfoModel = userInfoModel;
		this.context = context;
		options = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.ic_stub)
				.showImageForEmptyUri(R.drawable.noimage)
				.showImageOnFail(R.drawable.noimage).cacheInMemory()
				.cacheOnDisc().displayer(new RoundedBitmapDisplayer(5)).build();
		uid=Utils.getUid(context);
		RefreshDataThread(uid);

	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return activityListModels.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return activityListModels.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub

		LayoutInflater inflater = LayoutInflater.from(context);
		convertView = inflater.inflate(
				R.layout.fragment_indexclub4_import_layout, null);
		convertView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(context,
						ActivityReadingActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				intent.putExtra("actId", activityListModels.get(position)
						.getId());
				context.startActivity(intent);
			}
		});
		ImageView activity_list_item_img = (ImageView) convertView
				.findViewById(R.id.activity_list_item_img);
		TextView activity_list_item_name = (TextView) convertView
				.findViewById(R.id.activity_list_item_name);
		TextView activity_list_item_numperson = (TextView) convertView
				.findViewById(R.id.activity_list_item_numperson);
		Button activity_list_item_add = (Button) convertView
				.findViewById(R.id.activity_list_item_add);
		activity_list_item_name.setText(activityListModels.get(position)
				.getNames());
		activity_list_item_numperson.setText(activityListModels.get(position)
				.getApplied());
		if (activityListModels.get(position).getAdd().equals("0")) {
			activity_list_item_add.setText(R.string.attend);
			activity_list_item_add.setTextColor(0xff3eb251);
			activity_list_item_add.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					System.out.println(userInfoModel.getPhone()
							+ userInfoModel.getEmail());
					if (activityListModels.get(position).getIs_online()
							.equals("0")) {
						if (!(userInfoModel.getPhone().equals(""))
								&& !(userInfoModel.getEmail().equals(""))) {
							if (!activityListModels.get(position).getGold()
									.equals("0")) {
								new AlertDialog.Builder(context)
										.setTitle(
												context.getResources()
														.getString(
																R.string.l_xb140))
										.setIcon(R.drawable.icon)
										.setMessage(
												context.getResources()
														.getString(
																R.string.l_xb163)
														+ activityListModels
																.get(position)
																.getNames()
														+ context
																.getResources()
																.getString(
																		R.string.l_xb164)
														+ activityListModels
																.get(position)
																.getGold()
														+ context
																.getResources()
																.getString(
																		R.string.l_xb165))
										.setPositiveButton(
												context.getResources()
														.getString(
																R.string.l_xb163),
												new DialogInterface.OnClickListener() {

													@Override
													public void onClick(
															DialogInterface arg0,
															int arg1) {
														Add_activity(activityListModels
																.get(position)
																.getId());
													}
												})
										.setNegativeButton(
												context.getResources()
														.getString(
																R.string.l_xb166),
												new DialogInterface.OnClickListener() {

													@Override
													public void onClick(
															DialogInterface arg0,
															int arg1) {

													}
												}).show();
							} else {
								Add_activity(activityListModels.get(position)
										.getId());
							}
						} else {
							// Utils.showMessage(
							// ActivityReadingActivity.this,
							// getResources().getString(
							// R.string.email_and_phone_is_required));
							Toast toast;
							toast = Toast
									.makeText(
											context,
											context.getResources()
													.getString(
															R.string.email_and_phone_is_required),
											100);
							toast.setGravity(Gravity.CENTER, 0, 0);
							toast.show();

							Intent intent = new Intent(context,
									MyDataActivity.class);
							intent.putExtra("uid", Utils.getUid(context));
							context.startActivity(intent);

						}
					}else{
						if (!activityListModels.get(position).getGold()
								.equals("0")) {
							new AlertDialog.Builder(context)
									.setTitle(
											context.getResources()
													.getString(
															R.string.l_xb140))
									.setIcon(R.drawable.icon)
									.setMessage(
											context.getResources()
													.getString(
															R.string.l_xb163)
													+ activityListModels
															.get(position)
															.getNames()
													+ context
															.getResources()
															.getString(
																	R.string.l_xb164)
													+ activityListModels
															.get(position)
															.getGold()
													+ context
															.getResources()
															.getString(
																	R.string.l_xb165))
									.setPositiveButton(
											context.getResources()
													.getString(
															R.string.l_xb163),
											new DialogInterface.OnClickListener() {

												@Override
												public void onClick(
														DialogInterface arg0,
														int arg1) {
													Add_activity(activityListModels
															.get(position)
															.getId());
												}
											})
									.setNegativeButton(
											context.getResources()
													.getString(
															R.string.l_xb166),
											new DialogInterface.OnClickListener() {

												@Override
												public void onClick(
														DialogInterface arg0,
														int arg1) {

												}
											}).show();
						} else {
							Add_activity(activityListModels.get(position)
									.getId());
						}
					}
				}
			});
		} else if (activityListModels.get(position).getAdd().equals("1")) {
			activity_list_item_add.setText(R.string.Already_attend);
			activity_list_item_add.setTextColor(R.color.gray);
		}
		ImageLoader.getInstance().displayImage(
				Constants.BadiDownImgUrl
						+ activityListModels.get(position).getImage()
						+ Constants.appPhoto4img, activity_list_item_img,
				options);

		return convertView;
	}

	private void Add_activity(final String clubid) {
		Utils.showPrgress(context);
		MyThreadTool.fixedThreadPool.execute(new Runnable() {
			@Override
			public void run() {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("uid", Utils.getUid(context));
				map.put("aid", clubid);
				//
				String content = Utils.sendRequest(map, Constants.BadiUrl
						+ "add_activity");
				System.out.println("add_activity" + content);
				if (content != null) {
					final Results results = Utils.checkResult_NNN(context,
							content);
					//
					// "返回的数据是:" + content + " " + results.getRetmsg());
					if (results != null && !results.getRetmsg().equals("null")) {
						mes = new Message();
						bun = new Bundle();
						mes.what = 2;
						bun.putString("结果", results.getRetmsg());
						mes.setData(bun);
						handler.sendMessage(mes);
					} else {
						handler.sendEmptyMessage(3);
					}
				} else {
					handler.sendEmptyMessage(1);
				}
			}
		});
	}
	public void RefreshDataThread(final String uid) {
		
				MyThreadTool.fixedThreadPool.execute(new Runnable() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
		
						Map<String, Object> map = new HashMap<String, Object>();
						map.put("id", uid);
						map.put("languageType", com.badibadi.mytools.Dialog
								.getSystemLanguageType(context));
						String content = Utils.sendRequest(map, Constants.BadiUrl
								+ "userDataShow");
						if (content != null) {
							// ("结果是:" + content);
							Results results = Utils.checkResult_NNN(context,
									content);
							if (results != null && results.getRetmsg() != null) {
								//
								// ("得到的结果是：" + results.getRetmsg());
								try {
									userInfoModel = JSONUtils.getEntityByJsonString(
											results.getRetmsg(), UserInfoModel.class);
									userInfoModel.setUid(uid);
									System.out.println("userInfoModel"
											+ results.getRetmsg());
									// handler.sendEmptyMessage(4);
								} catch (JSONException e) {
									// ("解析出错");
		
								} catch (Exception e) {
									// TODO Auto-generated catch block
									//
		
								}
							} else {
		
							}
						} else {
							handler.sendEmptyMessage(1);
						}
					}
				});
			}

}
